<template>
	<el-drawer
	  v-model="dialog.visible"
	  :title="dialog.title"
	  append-to-body
	  @close="closeDialog"
	  :close-on-click-modal="false"
	  size="750"
	>
		<el-steps :active="active"  align-center finish-status="success">
			<el-step title="Step 1" description="输入数据结构" />
			<el-step title="Step 2" description="清洗与规范" />
			<el-step title="Step 3" description="输出" />
			<el-step title="Step 4" description="完成" />
		</el-steps>
		
		<div class="step-content">
			<div v-if="active==0">
				<el-form
					ref="contentFormRef"
					:model="contentFormData"
					:rules="contentFormRules"
					label-width="120px"
				>
					<el-form-item label="取值字段标识" prop="valueFieldIdentifier">
						<el-input v-model="contentFormData.valueFieldIdentifier" placeholder="请输入取值字段(层级提取请用英文.分隔,如:result.data)" />
<!-- 						<div style="color: var(--el-text-color-regular);">
							$key:value取值解释:如下结构{key1:{key2:value2}},取key1对应得值，取值字段填写$key:value
						</div> -->
					</el-form-item>
					
					<el-form-item label="取值字段类型" prop="valueFieldType">
						<Dict v-model="contentFormData.valueFieldType" code="field_type" style="width: 100%;" />
					</el-form-item>
					
					<el-form-item label="取值Json字段" prop="valueFieldJsonReturnType" v-if="contentFormData.valueFieldType=='map'">
						<el-radio-group v-model="contentFormData.valueFieldJsonReturnType">
							<el-radio label="Key字段" :value="'key'" />
							<el-radio label="Value字段"  :value="'value'"/>
							<el-radio label="All字段"  :value="'all'"/>
						</el-radio-group>
					</el-form-item>
					
				</el-form>
			</div>
			
			<div v-if="active==1">
				<div class="section-title">
				  <span class="title-form_primary">字段信息</span>
				  <div>
					  <el-button 
						type="primary" 
						link 
						@click="handleParseJson" 
					  >
						<el-icon><Document /></el-icon>解析JSON
					  </el-button>
					  
					  <el-button type="primary" link @click="handleAddField">
						<el-icon><Plus /></el-icon>添加字段
					  </el-button>
					  
				  </div>
				</div>
				
				<!-- JSON解析对话框 -->
				<el-dialog
					v-model="jsonDialog.visible"
					title="JSON解析"
					width="50%"
					append-to-body
					destroy-on-close
				>
					<el-form>
						<el-form-item>
							<MonacoEditor
								v-model="jsonDialog.content"
								language="json"
								:options="{ 
									theme: 'vs-dark',
									minimap: { enabled: false },
									lineNumbers: 'on',
									scrollBeyondLastLine: false,
									wordWrap: 'on',
									automaticLayout: true
								}"
								style="height: 300px"
							/>
						</el-form-item>
					</el-form>
					<template #footer>
						<el-button @click="jsonDialog.visible = false">取 消</el-button>
						<el-button type="primary" @click="parseJsonContent">解 析</el-button>
					</template>
				</el-dialog>
				
				<div class="param-model-content">
					<draggable
						v-model="fieldDefinitions"
						:animation="150"
						handle=".drag-handle"
						item-key="identifier"
						:component-data="{
						  tag: 'div',
						  type: 'transition-group',
						  name: !drag ? 'flip-list' : null
						}"
						@start="drag = true"
						@end="drag = false"
					>
						<template #item="{ element: row, index }">
							<div class="param-model-content-row">
								<el-button class="drag-handle" link>
									<el-icon><Rank /></el-icon>
								</el-button>
								<div class="param-info">
									<div class="param-name">
										输入字段名:{{ row.inputFieldName }} || 输入字段标识:{{ row.inputFieldIdentifier }}
									</div>
									<div class="param-detail">
										<span>输出字段名: {{ row.outputFieldName }}</span>
										<span>输出字段标识: {{ row.outputFieldIdentifier }}</span>
										<el-tag :type="row.outputValueFromInput=='input' ? 'success' : 'info'" size="small">
											{{ row.outputValueFromInput =='input' ? '输入值' : '默认值' }}
										</el-tag>
									</div>
								</div>
								<div class="param-actions">
									<el-button type="primary" link @click="handleEditField(index,row)">
										<el-icon><Edit /></el-icon>编辑
									</el-button>
									<el-button type="danger" link @click="removeField(index)">
										<el-icon><Delete /></el-icon>删除
									</el-button>
								</div>
							</div>
						</template>
					</draggable>
					<div v-if="fieldDefinitions.length === 0" class="empty-tip">
						暂无字段，请点击上方按钮添加
					</div>
				</div>
			</div>
			
			<div v-if="active==2">
				
				<div class="section-title">
				  <span class="title-form_primary">输出信息</span>
				  <el-button type="primary" link @click="handleAddOutputTarget">
				    <el-icon><Plus /></el-icon>添加输出
				  </el-button>
				</div>
				
				<div class="param-model-content">
					<draggable
						v-model="outputDefinitions"
						:animation="150"
						handle=".drag-handle"
						item-key="identifier"
						:component-data="{
						  tag: 'div',
						  type: 'transition-group',
						  name: !drag ? 'flip-list' : null
						}"
						@start="drag = true"
						@end="drag = false"
					>
						<template #item="{ element: row, index }">
						  <div class="param-model-content-row">
							<el-button 
							  class="drag-handle" 
							  link
							>
							  <el-icon><Rank /></el-icon>
							</el-button>
							<div class="param-info">
							  <div class="param-name">{{ row.type }}</div>
							  <div class="param-detail">
								<span v-if="row.type=='OLTP'">表名: {{ row.table }}</span>
								<span v-if="row.type=='OLTP'">主键: {{ row.primarykey }}</span>
								<span v-if="row.type=='MQTT'">主题: {{ row.name }}</span>
								<span v-if="row.type=='MQTT'">QoS等级: {{ row.qos }}</span>
								<span v-if="row.type=='MQTT'">留存: {{ row.retained === '0' ? '否' : '是' }}</span> 
								<span v-if="row.type=='REDIS'">常量缓存:  {{ row.fixedRedisKey === '0' ? '否' : '是' }}</span>
								<span v-if="row.type=='REDIS' && row.fixedRedisKey=='0'">缓存取值字段:  {{ row.redisKeyValueField}}</span>
								<span v-if="row.type=='REDIS' && row.fixedRedisKey=='1'">常量缓存Key值:  {{ row.fixedRedisKeyValue}}</span>
								<el-tag :type="row.fieldStandardSame=='1' ? 'success' : 'info'" size="small">
								  {{ row.fieldStandardSame=='1' ? '一致' : '不一致' }}
								</el-tag>
							  </div>
							</div>
							<div class="param-actions">
							  <el-button type="primary" link @click="handleEditOutputTarget(index,row)">
								<el-icon><Edit /></el-icon>编辑
							  </el-button>
							  <el-button type="danger" link @click="removeOutputTarget(index)">
								<el-icon><Delete /></el-icon>删除
							  </el-button>
							</div>
						  </div>
						</template>
					</draggable>
					<div v-if="outputDefinitions.length === 0" class="empty-tip">
						暂无输出信息，请点击上方"添加输出"按钮添加
					</div>
				</div>
			</div>
			
			<div v-if="active==3">
				<el-form
					ref="completedFormRef"
					:model="completedFormData"
					:rules="completedFormRules"
					label-width="120px"
				>
					<el-form-item label="是否启用" prop="enabled" >
						<el-radio-group v-model="completedFormData.enabled" >
						  <el-radio value="0">禁用</el-radio>
						  <el-radio value="1">启用</el-radio>
						</el-radio-group>
					</el-form-item>
					
					<el-form-item label="备注" prop="remark" >
						<el-input v-model="completedFormData.remark" type="textarea" maxlength="250" placeholder="请输入备注信息" show-word-limit />
					</el-form-item>
				</el-form>
			</div>
		</div>
	
		<template #footer>
		  <div class="dialog-footer">
			<el-button type="primary" @click="preStep"  :loading="loading" v-if="active!=0  ||  !(isEdit==true && active==0 )">上一步</el-button>
			<el-button type="primary" @click="nextStep"  :loading="loading" v-if="active!=3">下一步</el-button>
			<el-button type="primary" @click="submitForm" v-if="active==3"  :loading="loading">确 定</el-button>
			<el-button @click="closeDialog" :loading="loading">取 消</el-button>
		  </div>
		</template>
		
		<EditFieldDrawer  ref="editFieldDrawerRef" @success="handleEditFieldSuccess"></EditFieldDrawer>
		<EditOutputTargetDrawer  ref="editOutputTargetDrawerRef" @success="handleEditOutputTargetSuccess"></EditOutputTargetDrawer>
		
	</el-drawer>
</template>

<script lang="ts" setup>
	
	import { ref } from "vue";
	import MonacoEditor from '@/components/MonacoEditor/index.vue'
	import EditFieldDrawer from '@/components/DataWorkflow/components/EditFieldDrawer.vue'
	import EditOutputTargetDrawer from '@/components/DataWorkflow/components/EditOutputTargetDrawer.vue'
	
	import { Plus, Delete, Edit, Rank, Document } from '@element-plus/icons-vue';
	import draggable from 'vuedraggable';
	import type {FormRules } from 'element-plus'
	import { ElMessage } from "element-plus";
	import { reactive } from "vue";
	import { onMounted } from "vue";
	import { parseJsonToFields } from '@/utils/jsonParser';
	
	// 修改 Monaco Editor worker 配置
	// import * as monaco from 'monaco-editor';
	// import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
	// import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
	// import 'monaco-editor/esm/vs/basic-languages/sql/sql.contribution';
	import { ElMessageBox } from "element-plus";
	
	const loading = ref(false);
	const dialog = ref({
		visible:false,
		title:'',
	});
	const editFieldDrawerRef = ref();
	const editOutputTargetDrawerRef = ref();
	const active = ref<number>(0);
	
	const fieldDefinitions = ref<any[]>([]);
	const outputDefinitions = ref<any[]>([]);
	
	
	const drag = ref(false);
	
	const contentFormRef=ref();
	const contentFormRules=reactive<FormRules>({
		valueFieldType: [{ required: true, message: "请输入取值字段类型.", trigger: "blur" }],
		valueFieldJsonReturnType: [{ required: true, message: "请选择Json内容取值.", trigger: "blur" }],
	});
	
	
	const contentFormData = ref<any>({
		sql: '',
	});
	
	const completedFormRef=ref();
	const completedFormRules=reactive<FormRules>({
		name: [{ required: true, message: "请选择数据任务名称.", trigger: "blur" }],
		enabled: [{ required: true, message: "请选择数据任务是否启用.", trigger: "blur" }],
	});
	const completedFormData = ref<any>({
		enabled: '1',
	});
	
	const preStep = () => {
		if(active.value>0){
			active.value-=1
		}
		else{
			active.value=0
		}
	}
	
	const nextStep = () => {
		if(0==active.value){
			contentFormRef.value.validate((isValid: boolean) => {
				if (isValid) {
					active.value=1
				}
			});
		}
		else if(1==active.value){
			if(!fieldDefinitions || fieldDefinitions.value.length<=0){
				ElMessage.warning('请添加清洗与规范内容.');
				return;
			}
			active.value=2
		}
		else if(2==active.value){
			active.value=3
		}
		else if(3==active.value){
			active.value=4
		}
	}
	
	//输出
	const handleAddOutputTarget = () => {
		editOutputTargetDrawerRef.value.openDialog(-1,null,fieldDefinitions.value,'add');
	};
	
	const handleEditOutputTarget = (index: number,data:any) => {
		editOutputTargetDrawerRef.value.openDialog(index,data,fieldDefinitions.value,'edit');
	};
	
	const removeOutputTarget = (index: number) => {
		ElMessageBox.confirm('确认删除该输出吗？', '提示', {
				type: 'warning'
		}).then(() => {
			outputDefinitions.value?.splice(index, 1);
			ElMessage.success('删除成功');
		});
	};
	
	const handleEditOutputTargetSuccess=(index:number,data:any)=>{
		try {
			if (!outputDefinitions.value) {
				outputDefinitions.value = [];
			}
			if (index > -1) {
				outputDefinitions.value[index] = data;
			} else {
				outputDefinitions.value.push(data);
			}
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}
	
	//清洗与规范
	const handleAddField = () => {
		editFieldDrawerRef.value.openDialog(-1,null,'add');
	};
	
	const handleEditField = (index: number,data:any) => {
		editFieldDrawerRef.value.openDialog(index,data,'edit');
	};
	
	const removeField = (index: number) => {
		ElMessageBox.confirm('确认删除该字段吗？', '提示', {
				type: 'warning'
		}).then(() => {
			fieldDefinitions.value?.splice(index, 1);
			ElMessage.success('删除成功');
		});
	};
	
	const handleEditFieldSuccess=(index:number,data:any)=>{
		try {
			if (!fieldDefinitions.value) {
				fieldDefinitions.value = [];
			}
			if (index > -1) {
				fieldDefinitions.value[index] = data;
			} else {
				fieldDefinitions.value.push(data);
			}
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}
	
	const editRow=ref<any>();
	const isEdit=ref<boolean>(false);
	const editRowIndex=ref<number>(); 
	
	async function openDialog(index: number,_row?: any, _type?: string) {
		editRowIndex.value=index;
		dialog.value.visible=true;
		dialog.value.title='编辑';
		isEdit.value=true;
		active.value=0;
		editRow.value=_row;
		isEdit.value=true;
		
		if(editRow.value?.flow){
			completedFormData.value.enabled=editRow.value?.flow?.enabled;
			completedFormData.value.remark=editRow.value?.flow?.remark;
			if(editRow.value?.flow?.content){
				const content=JSON.parse(editRow.value?.flow?.content);
				if(content){
					contentFormData.value.valueFieldIdentifier=content?.valueFieldIdentifier||"";
					contentFormData.value.valueFieldType=content?.valueFieldType||"";
					contentFormData.value.valueFieldJsonReturnType=content?.valueFieldJsonReturnType||"";
				}
			}
			if(editRow.value?.flow?.standardFields){
				const standardFields=JSON.parse(editRow.value?.flow?.standardFields);
				if(standardFields){
					fieldDefinitions.value=standardFields;
				}
			}
			if(editRow.value?.flow?.output){
				const output=JSON.parse(editRow.value?.flow?.output);
				if(output){
					outputDefinitions.value=output;
				}
			}
		}else{
			editRow.value.flow={}
		}
	}
	
	/**
	 * 信息保存
	 */
	async function submitForm() {
		if (!completedFormRef.value) return;
		await completedFormRef.value.validate();
		loading.value = true;
		try {
			loading.value = true;
			editRow.value.flow={
				enabled:completedFormData.value.enabled,
				remark:completedFormData.value.remark,
				content:JSON.stringify({
					valueFieldIdentifier:contentFormData.value?.valueFieldIdentifier||"",
					valueFieldType:contentFormData.value?.valueFieldType||"",
					valueFieldJsonReturnType:contentFormData.value?.valueFieldJsonReturnType||"",
				}),
				standardFields:JSON.stringify(fieldDefinitions.value),
				output:JSON.stringify(outputDefinitions.value),
			}
			emits('confirm',editRow.value,editRowIndex.value);
			active.value=4;
			loading.value = false;
			closeDialog();
		} catch (e:any) {
			ElMessage.error(e.message);
		}
	}
	
	const emits = defineEmits(['closeDialog','confirm'])
	const closeDialog=()=>{
		dialog.value.visible=false;
		dialog.value.title="";
		emits('closeDialog')
		resetForm();
	}
	/**
	 * 重置表单
	 */
	function resetForm() {
		isEdit.value=false;
		if(completedFormRef.value){
			completedFormRef.value.resetFields();
			completedFormRef.value.clearValidate();
		}
		
		editRow.value={};
		completedFormData.value.enabled="0";
		completedFormData.value.remark="";
		
		contentFormData.value={};
		fieldDefinitions.value=[];
		outputDefinitions.value=[];
	}	
	
	defineExpose({
	  openDialog,closeDialog
	});
	
	// JSON解析对话框数据
	const jsonDialog = ref({
		visible: false,
		content: ''
	});
	
	// 处理JSON解析按钮点击
	const handleParseJson = () => {
		jsonDialog.value.visible = true;
		// 如果有valueFieldIdentifier，预填充示例JSON结构
		if (contentFormData.value.valueFieldIdentifier) {
			const structure: any = {};
			const paths = contentFormData.value.valueFieldIdentifier.split('.');
			let current = structure;
			paths.forEach((path: string, index: number) => {
				if (index === paths.length - 1) {
					current[path] = contentFormData.value?.valueFieldType === 'array' ? [{}] : {};
				} else {
					current[path] = {};
					current = current[path];
				}
			});
			jsonDialog.value.content = JSON.stringify(structure, null, 2);
		}
	};
	
	// 解析JSON内容
	const parseJsonContent = () => {
		try {
			const jsonContent = JSON.parse(jsonDialog.value.content);
			let targetJson = jsonContent;

			// 如果设置了取值字段标识，则根据路径获取目标对象
			if (contentFormData.value.valueFieldIdentifier) {
				const paths = contentFormData.value.valueFieldIdentifier.split('.');
				targetJson = paths.reduce((obj: any, path: string) => obj?.[path], jsonContent);

				if (contentFormData.value?.valueFieldType === 'array' && Array.isArray(targetJson)) {
					targetJson = targetJson[0]; // 取数组第一个元素作为结构模板
				}
			}

			if (!targetJson) {
				throw new Error('无法找到指定路径的数据');
			}

			// 解析字段
			const fields = parseJsonToFields(targetJson);
			
			// 添加新字段（避免重复）
			fields.forEach((field:any) => {
				const exists = fieldDefinitions.value.some(
					existingField => existingField.inputFieldIdentifier === field.inputFieldIdentifier
				);
				if (!exists) {
					fieldDefinitions.value.push(field);
				}
			});

			jsonDialog.value.visible = false;
			ElMessage.success('解析成功');
		} catch (error: any) {
			ElMessage.error('JSON解析失败: ' + error.message);
		}
	};
	
	onMounted(() => {
	});

</script>

<style scoped>
	.step-content{
		background-color: aliceblue;
		margin-top: 8px;
		padding: 8px;
		padding-top: 16px;
	}
	
	.title-form_primary {
	    font-style: normal;
	    font-weight: 500;
	    font-size: 14px;
	    color: #1f2329;
	    position: relative;
	    padding-left: 5px;
	}
	.title-form_primary:before {
	  content: "";
	  width: 2px;
	  height: 14px;
	  background: var(--el-color-primary);
	  position: absolute;
	  top: 50%;
	  transform: translateY(-50%);
	  left: 0;
	}
	
	
	.section-title {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  margin-bottom: 16px;
	}
	
	
	.param-model-content {
	  padding: 16px;
	  background: var(--el-fill-color-light);
	  border-radius: 4px;
	}
	
	.param-model-content-row {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  padding: 12px 8px;
	  margin-bottom: 8px;
	  background: var(--el-bg-color);
	  border: 1px solid var(--el-border-color-lighter);
	  border-radius: 4px;
	  transition: all 0.3s;
	  
	  &:hover {
	    border-color: var(--el-border-color);
	    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	  }
	}
	
	.param-info {
	  flex: 1;
	}
	
	.param-name {
	  font-size: 14px;
	  font-weight: 500;
	  color: var(--el-text-color-primary);
	  margin-bottom: 4px;
	}
	
	.param-detail {
	  display: flex;
	  align-items: center;
	  gap: 16px;
	  color: var(--el-text-color-secondary);
	  font-size: 13px;
	}
	
	.param-actions {
	  display: flex;
	  gap: 8px;
	}
	
	.empty-tip {
	  text-align: center;
	  color: var(--el-text-color-secondary);
	  padding: 32px 0;
	}
	
	.drag-handle {
	  cursor: move;
	  margin-right: 8px;
	  color: var(--el-text-color-secondary);
	  
	  &:hover {
	    color: var(--el-text-color-primary);
	  }
	}
	
	.flip-list-move {
	  transition: transform 0.5s;
	}
	
	.no-move {
	  transition: transform 0s;
	}
	
	.ghost {
	  opacity: 0.5;
	  background: #c8ebfb;
	}
	
	.sql-editor-container {
		margin-bottom: 16px;
		border: 1px solid var(--el-border-color-light);
		border-radius: 4px;
		overflow: hidden;
	
		.sql-editor {
			height: 200px;
			border-radius: 4px;
		}
	
		.sql-tips {
			padding: 8px;
			background-color: var(--el-bg-color-page);
			border-top: 1px solid var(--el-border-color-light);
		}
	}
	
	.cron-tips {
	  margin-top: 8px;
	  font-size: 12px;
	  color: var(--el-text-color-secondary);
	  
	  p {
	    margin: 4px 0;
	  }
	}
	
	.cron-tag {
	  margin-right: 8px;
	  margin-bottom: 8px;
	  cursor: pointer;
	  
	  &:hover {
	    opacity: 0.8;
	  }
	}
	
	.cron-preview {
	  margin-top: 16px;
	  padding: 12px;
	  background: var(--el-fill-color-light);
	  border-radius: 4px;
	  
	  .expression {
	    color: var(--el-color-primary);
	    font-weight: bold;
	    margin-left: 8px;
	  }
	}
</style>